<template>
  <div v-loading.fullscreen.lock="loading" class="login-page"></div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAccountStore } from '../stores/account.js'
import { log } from '../utils/log'
import db from '../utils/localstorage'
const $request = inject('$request')
const loading = ref(true)
const route = useRoute()
const router = useRouter()
const accountStore = useAccountStore()

onMounted(async () => {
  const hash = window.location.hash.replace('#', '')
  if (hash) {
    const params = new URLSearchParams(window.location.hash.substring(1))
    log('params', params.get('id_token'))
    const nonce = db.get('google_nonce')
    loginByGoogle(params.get('id_token'), nonce)
  }
})

const loginByGoogle = async (id_token, nonce) => {
  try {
    const { data } = await $request.post('/authorization/google-callback', {
      id_token,
      nonce
    })
    if (!data.ok) {
      throw new Error(data.detail || 'Login failed')
    }
    db.remove('google_nonce')
    window.location.href = `/authorization?token=${data.result}`
  } catch (error) {
    log(error)
    ElMessage({
      message: error.message || error,
      type: 'error'
    })
    setTimeout(() => {
      router.replace('/airdrop')
    }, 500)
  }
}
</script>

<style lang="less" scoped>
.login-page {
  flex: 1;
  background: #000;
  background-size: 100%;
  position: relative;
}
</style>
